package za.co.johanmynhardt.web.feed;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import za.co.johanmynhardt.jee.entity.Post;
import za.co.johanmynhardt.jee.producer.PostListProducer;
import za.co.johanmynhardt.jee.repository.PostList;

/**
 * @author johan.mynhardt@thumbtribe.mobi
 * @version 2011.1220
 */
@Local
@Stateless
public class FeedService {

	@Inject
	@PostList
	PostListProducer producer;

	public SyndFeed getAtomFeed() {
		return getFeed("atom_1.0");
	}

	public SyndFeed getRssFeed() {
		return getFeed("rss_2.0");
	}

	public SyndFeed getFeed(String format) {
		final String URI = "http://johanmynhardt.co.za/feed/atom";
		SyndFeed syndFeed = new SyndFeedImpl();
		syndFeed.setUri(URI);
		syndFeed.setAuthor("johanmynhardt.co.za");
		syndFeed.setLink(URI);
		syndFeed.setEncoding("UTF-8");
		syndFeed.setTitle("Posts from johanmynhardt.co.za");
		syndFeed.setDescription("Posts from johanmynhardt.co.za in Atom syndication format.");
		syndFeed.setFeedType(format);

		List<SyndEntry> syndEntries = new ArrayList<SyndEntry>();
		
		Date date = new Date(0L);
		
		for (Post post : producer.getPosts()) {
			if (post.getDate().after(date)) {
				date = post.getDate();
			}
			SyndEntry entry = getEntry(post);
			syndEntries.add(entry);
		}

		syndFeed.setPublishedDate(date);
		syndFeed.setEntries(syndEntries);

		return syndFeed;
	}
	
	private SyndEntry getEntry(Post post) {
		SyndEntry entry = new SyndEntryImpl();
		final String URI = "http://johanmynhardt.co.za/post.jsf?view=" + post.getId();
		entry.setUri(URI);
		entry.setLink(URI);
		entry.setAuthor(post.getUser() == null ? "Anonymous" : post.getUser().getName().concat(" ").concat(post.getUser().getSurname()));
		entry.setTitle(post.getTitle());
		entry.setPublishedDate(post.getDate());

		SyndContent summary = new SyndContentImpl();
		summary.setType("text/html");
		summary.setValue(post.getContent().length() > 150 ? post.getContent().substring(0, 150).concat("...") : post.getContent());
		
		entry.setDescription(summary);
		
		List<SyndContent> contents = new ArrayList<SyndContent>();
		SyndContent content = new SyndContentImpl();
		content.setType("text/html");
		content.setValue(post.getContent());
		contents.add(content);
		
		entry.setContents(contents);

		return entry;
	}
}
